//
//  GetHumanDialerViewController.m
//  GetHumanDialer
//
//  Created by Jeffrey Palm on 12/19/08.
//  Copyright Jeffrey Palm 2008. All rights reserved.
//

#import "GetHumanDialerViewController.h"

@interface GetHumanDialerViewController (PrivateMethods)
- (void) lookUpNumber;
- (void) updateNumberField;
- (void) showGethuman:(NSString*)name phone:(NSString*)thePhone directions:(NSString*)theDirections valid:(BOOL)isValid;
- (void) startWorking:(NSString*)msg;
- (void) stopWorking;
- (NSString*) buf;
- (BOOL) isValidRange:(NSRange)r string:(NSString*)r;
- (void) setNeedsDisplay;
@end

@implementation GetHumanDialerViewController

- (IBAction)buttonClicked:(id)sender {
	NSString *c = nil;
	if (sender == button1) {
		c = @"1";
	} else if (sender == button2) {
		c = @"2";
	} else if (sender == button3) {
		c = @"3";
	} else if (sender == button4) {
		c = @"4";
	} else if (sender == button5) {
		c = @"5";
	} else if (sender == button6) {
		c = @"6";
	} else if (sender == button7) {
		c = @"7";
	} else if (sender == button8) {
		c = @"8";
	} else if (sender == button9) {
		c = @"9";
	} else if (sender == buttonStar) {
		c = @"*";
	} else if (sender == button0) {
		c = @"0";
	} else if (sender == buttonHash) {
		c = @"#";
	} else {
		NSLog(@"WTF %@", sender);
	}
	if ([[self buf] length] < 18) {
		[tmpBuf appendString:c];
		[self updateNumberField];
		NSLog(@"Have string %@", [self buf]);		
	}
}

- (IBAction)placeCall:(id)sender {
	NSLog(@"placeCall %@", [self buf]);
	[self lookUpNumber];
	
}

- (IBAction)back:(id)sender {
	if ([[self buf] length] > 0) {
		[tmpBuf deleteCharactersInRange:NSMakeRange(tmpBuf.length-1, 1)];
		[self updateNumberField];
	}
	NSLog(@"back %@", [self buf]);
}

- (IBAction)addContact:(id)sender {
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Add Contact?" message:@"NO!"
																								 delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
	[alert show];
	[alert release];	
}

- (void) lookUpNumber {
	
	NSLog(@"Looking up %@", [self buf]);
	
	// First canonoclize the number
	NSMutableString *number = [NSMutableString stringWithString:[self buf]];
	if ([number length] <= 0) return;
	char firstNumber = [number characterAtIndex:0];
	if (firstNumber == '1') {
		[number deleteCharactersInRange:NSMakeRange(0, 1)];
	}
	
	NSLog(@"lookUpNumber %@", number);
	
	/*
			<tr class="gray">
			<td nowrap=nowrap>Alamo
			</td>
			<td nowrap=nowrap>800&#8209;462&#8209;5266
			</td>
			<td>Direct to human.
			</td></tr>
	 */	 
	//
	// This could definitely be improved upon -- i.e. it sucks now
	//
	NSLog(@"Checking gethuman.com for %@...", number);
	[self startWorking:@"Checking gethuman.com..."];
	NSString *html = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://gethuman.com/"]];
	NSArray *lines = [html componentsSeparatedByString:@"\n"];
	NSString *name				= nil;
	NSString *phone				= nil;
	NSString *directions	= nil;
	BOOL			started			= FALSE;
	BOOL			shown				= FALSE;
	for (NSString *s in lines) {

		NSRange r;
		
		// Dont start until we see this: <tr class="white">
		if (!started) {
			r = [s rangeOfString:@"<tr class=\"white\">"];
			if ([self isValidRange:r string:s]) {
				started = TRUE;
			}
			continue;
		}
		if (name == nil) {			
			r = [s rangeOfString:@"<td nowrap=nowrap>"];
			if ([self isValidRange:r string:s]) {
				name = [s substringFromIndex:r.location+r.length];
				NSLog(@"Have name %@", name);
			}
		} else if (phone == nil) {
			r = [s rangeOfString:@"<td nowrap=nowrap>"];
			if ([self isValidRange:r string:s]) {
				phone = [[s substringFromIndex:r.location+r.length] stringByReplacingOccurrencesOfString:@"&#8209;" withString:@""];
				if ([phone isEqualToString:number]) {
					NSLog(@"We have a match for %@ with %@", phone, name);
				} else  {
					name = nil;
					phone = nil;
				}
				continue;
			}
			r = [s rangeOfString:@"<td nowrap=nowarp><a href"];
			if ([self isValidRange:r string:s]) {
				NSUInteger start = r.location+r.length;
				NSLog(@"start=%d",start);
				NSRange r2 = [s rangeOfString:@">" options:NSCaseInsensitiveSearch range:NSMakeRange(start, s.length-start)];
				if (r2.location >= 0) {
					phone = [[s substringFromIndex:r2.location+r2.length] stringByReplacingOccurrencesOfString:@"&#8209;" withString:@""];
					phone = [phone stringByReplacingOccurrencesOfString:@" " withString:@""];
					
					// Strip off the trailing '</a>'
					NSRange r3 = [phone rangeOfString:@"<"];
					if ([self isValidRange:r3 string:phone]) {
						phone = [phone substringToIndex:r3.location];
					}
					if ([phone isEqualToString:number]) {
						NSLog(@"We have a match for %@ with %@", phone, name);
					} else  {
						name = nil;
						phone = nil;
					}
					continue;
				}
			}
		} else if (directions == nil) {
			r = [s rangeOfString:@"<td>"];
			if ([self isValidRange:r string:s]) {
				directions = [s substringFromIndex:r.location+r.length];
				NSLog(@"Have directions %@", directions);
				[self showGethuman:name phone:phone directions:directions valid:TRUE];
				shown = TRUE;
				break;
			}
		}
	}
	[self stopWorking];
	if (!shown) {
		[self showGethuman:@"Not found" phone:phone directions:@"Sorry, we couldn't find human :(" valid:FALSE];
	}
}

- (void)threadedUpdateStatus:(NSString*)msg {
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	[self updateStatus:msg];
  [pool release];
}

- (void) startWorking:(NSString*)msg {
	[NSThread detachNewThreadSelector:@selector(threadedUpdateStatus:) toTarget:self withObject:msg];
	[spinner startAnimating];
	//[spinner performSelectorOnMainThread:@selector(startAnimating:) waitUntilDone:YES];
}

- (void) stopWorking {
	[spinner stopAnimating];
//	[spinner performSelectorOnMainThread:@selector(stopAnimating:) waitUntilDone:YES];
}

- (NSString*) buf {
	[self.navigationItem title];
}

- (BOOL) isValidRange:(NSRange)r string:(NSString*)s {
	return r.location >= 0 && r.location < s.length;
}

-(void) setTextAndUpdate:(NSString*)msg {
	[mainText setText:msg];
	[self.view setNeedsDisplay];
}

- (void) updateStatus:(NSString*)msg {
	[self performSelectorOnMainThread:@selector(setTextAndUpdate:) withObject:msg waitUntilDone:YES];
}


- (void) showGethuman:(NSString*)name phone:(NSString*)thePhone directions:(NSString*)theDirections valid:(BOOL)isValid {
	NSLog(@"Showing %@ (%@) : %@", name, thePhone, theDirections);
	[mainLabel performSelectorOnMainThread:@selector(setText:) withObject:name waitUntilDone:YES];
	[self updateStatus:theDirections];
	
	numberToDial = [thePhone copy];
	
	// open a alert with an OK and cancel button
	NSString *title;
	NSString *msg;
	if (isValid) {
		title = [NSString stringWithFormat:@"Dial %@?", name];
		msg = [NSString stringWithFormat:@"%@\n\"%@\"", thePhone, theDirections];
	} else {
		title = @"Dial?";
		msg = thePhone;
	}
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:msg
																								 delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
	[alert show];
	[alert release];
}

#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
	NSLog(@"have button index %d", buttonIndex);
	if (buttonIndex == 1) {
		// Place a new page in the invisible webbrowser and click a call link
		NSString *urlString = [@"tel://" stringByAppendingString:numberToDial];
		NSLog(@"phone url %@", urlString);
		[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];		
	}
	[self setTextAndUpdate:@""];
}

// if s is nil we remove a character
- (void) updateNumberField {
		[self.navigationItem performSelectorOnMainThread:@selector(setTitle:) withObject:tmpBuf waitUntilDone:YES];
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
  [super viewDidLoad];
	mainText.backgroundColor = [UIColor blackColor];
	mainLabel.font = [UIFont boldSystemFontOfSize:12.0];
	UIFont *font = [UIFont boldSystemFontOfSize:16.0];
	mainText.font = font;
	if (TESTING) {
		[self.navigationItem setTitle:@"8004625266"]; // alamo
	}
	tmpBuf = [[NSMutableString alloc] initWithString:[self buf]];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}


- (void)dealloc {
    [super dealloc];
	[tmpBuf release];
}

@end
